package com.wfc.servlet.user;

import com.wfc.entity.User;
import com.wfc.food.HelloServlet;
import com.wfc.service.UserService;
import com.wfc.service.serviceImpl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/checkLogin")
public class checkLogin extends HelloServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //从request中获取所有的cookie
        Cookie[] cookies = request.getCookies();
        String username = null;
        String password = null;;

        if(cookies != null) {
            //遍历cookie
            for(Cookie cookie : cookies) {
                if("username".equals(cookie.getName())) {//看cookie的name是不是与cookie的名字匹配
                    username = cookie.getValue();
                }else if("password".equals(cookie.getName())){
                    password = cookie.getValue();
                }
            }
        }
        if(username != null && password != null ) {
            //获取用户信息
            UserService userService = new UserServiceImpl();
            User news_user1 = userService.ServiceByUsername(username);
            HttpSession session = request.getSession();
            //session存用户信息
            session.setAttribute("user",news_user1);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }
}
